import React, { Component } from 'react';
import { Button, Table, Popconfirm, Icon, Tag, Tooltip, Empty } from 'antd';
import cn from 'classnames';
import Search from 'antd/lib/input/Search';
import Loading from '@components/loading';
import { getOnedayStrategtList, deleteOnedayStrategy, getAllHasPocOnedayList } from '@api/task';
import { get, pickBy } from 'lodash';
import ConfigModal from './components/config-modal';
import EmptyDataImg from '@images/empty-data-blue.png';
import './index.less';

class StrategyTemplate extends Component {
  constructor(props) {
    super(props);

    this.state = {
      page: 1,
      pageSize: 10,
      search: '',

      loaded: false,
      templates: [],
      onedays: [],
      total: 0,
      realTotal: 0,
      isLoadingData: false,
      configModalVisible: false,
      expandedRowKeys: [],
      currentTemplate: null
    };
  }

  componentDidMount() {
    const query = get(this.props, 'history.location.query');
    this.setState(
      { search: get(query, 'name', ''), page: 1, pageSize: 10 },
      this.loadStrategyTemplates
    );
    this.loadOnedays();
  }

  loadStrategyTemplates = () => {
    const { page, pageSize, search } = this.state;
    this.setState({ isLoadingData: true });
    const filter = pickBy(
      {
        page,
        pageSize,
        search
      },
      i => Boolean(i)
    );
    getOnedayStrategtList(filter)
      .then(res => {
        const templates = get(res, 'data.data.list', []);
        const total = get(res, 'data.data.count', 0);
        const body = {
          templates,
          total,
          loaded: true
        };
        if (total !== 0) {
          body.realTotal = total;
        }
        this.setState(body);
      })
      .finally(() => {
        this.setState({
          loaded: true,
          isLoadingData: false
        });
      });
  };

  loadOnedays = () => {
    getAllHasPocOnedayList().then(res => {
      const onedays = get(res, 'data.data.list', []).sort((a, b) => {
        return a.created > b.created ? -1 : 1;
      });
      this.setState({
        onedays
      });
    });
  };

  afterConfigStrategy = () => {
    this.setState(
      {
        configModalVisible: false
      },
      this.loadStrategyTemplates
    );
  };

  wrapOnEdit = row => e => {
    e.stopPropagation();
    this.setState({
      configModalVisible: true,
      currentTemplate: row
    });
  };

  getColumns = () => {
    const columns = [
      {
        title: '模板名称',
        dataIndex: 'name'
      },
      {
        title: '插件数量',
        dataIndex: 'oneday_detail_oids.length'
      },
      {
        title: '操作',
        key: 'operations',
        render: row => {
          const id = row._id;
          const operations = (
            <div className="st-table-operations">
              <span className="st-table-operations__edit" onClick={this.wrapOnEdit(row)}>
                编辑
              </span>
              <Popconfirm
                title="确认删除该策略模板吗?"
                onConfirm={e => {
                  e.stopPropagation();
                  this.deleteOnedayStrategy(id);
                }}
                onCancel={e => e.stopPropagation()}
              >
                <span className="st-table-operations__delete" onClick={e => e.stopPropagation()}>
                  删除
                </span>
              </Popconfirm>
            </div>
          );
          return operations;
        }
      }
    ];
    return columns;
  };

  renderExpanRow = row => {
    const onedays = get(row, 'oneday_detail_oids', []).filter(oneday =>
      Boolean(get(oneday, 'name'))
    );
    return (
      <div onClick={this.handleJumpToOneday}>
        {onedays.map((oneday, index) => (
          <Tooltip key={index} title={get(oneday, 'name')}>
            <Tag className="vul-tag" data-to={get(oneday, '_id')}>
              {get(oneday, 'name')}
            </Tag>
          </Tooltip>
        ))}
      </div>
    );
  };

  handleJumpToOneday = e => {
    const onedayId = get(e, 'target.dataset.to');
    if (onedayId) {
      window.open(`/vul/oneday-detection/${onedayId}`);
    }
  };

  deleteOnedayStrategy = id => {
    deleteOnedayStrategy(id).then(this.loadStrategyTemplates);
  };

  onTableChange = ({ current: page, pageSize }) => {
    document.getElementsByClassName('ant-layout-content')[0].scrollTop = 0;
    this.setState(
      {
        page,
        pageSize
      },
      this.loadStrategyTemplates
    );
  };

  onSearch = search => {
    this.setState({ search, page: 1, pageSize: 10 }, this.loadStrategyTemplates);
  };

  wrapOnConfigModalVisibleChange = (visible, currentTemplate = null) => () => {
    this.setState({
      configModalVisible: visible,
      currentTemplate
    });
  };

  onExpandedRowsChange = keys => {
    this.setState({
      expandedRowKeys: keys
    });
  };

  render() {
    const {
      total,
      realTotal,
      page,
      pageSize,
      templates,
      isLoadingData,
      loaded,
      configModalVisible,
      onedays,
      expandedRowKeys,
      currentTemplate,
      search
    } = this.state;
    const columns = this.getColumns();
    const pagination = {
      current: page,
      pageSize: pageSize,
      total: total,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: total => `共${total}条`
    };

    let body;

    if (!loaded) {
      body = <Loading />;
    } else {
      body = [
        <div className="st-operations" key="0">
          <div className="st-operations__left">
            <Button type="primary" onClick={this.wrapOnConfigModalVisibleChange(true)}>
              添加漏洞策略模板
            </Button>
          </div>
          <div className="st-operations_right">
            <Search
              onSearch={this.onSearch}
              placeholder="请输入模板名称"
              enterButton
              defaultValue={search}
            />
          </div>
        </div>,
        total ? (
          <div className="st-table" key="1">
            <p className="st-table__info">共有 &quot;{total}&quot; 个漏洞策略模板</p>
            <Table
              className="st-table__body"
              rowKey="_id"
              dataSource={templates}
              columns={columns}
              pagination={pagination}
              onChange={this.onTableChange}
              expandedRowRender={this.renderExpanRow}
              loading={{ spinning: isLoadingData, tip: '加载中' }}
              locale={{
                emptyText: (
                  <Empty
                    description={isLoadingData ? ' ' : '暂无数据'}
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                  />
                )
              }}
              expandRowByClick={true}
              expandedRowKeys={expandedRowKeys}
              onExpandedRowsChange={this.onExpandedRowsChange}
              rowClassName={record => {
                if (expandedRowKeys.indexOf(record._id) !== -1) {
                  return 'expaned';
                }
              }}
            />
          </div>
        ) : (
          <Empty
            image={EmptyDataImg}
            imageStyle={{
              margin: '120px 0 24px',
              height: 296
            }}
            description={
              <div>
                <span style={{ color: '#2A2B30' }}>您还未创建过漏洞策略模版</span>
                <p style={{ marginTop: 8, color: '#999EA8' }}>
                  创建资产探测或漏洞普查任务可以直接选择事先配置的漏洞策略模版
                  <br />
                  您可以通过左上角按钮添加
                </p>
              </div>
            }
          />
        )
      ];
    }

    return (
      <div
        className={cn(
          'strategy-template',
          { 'strategy-template_no-data': !realTotal && loaded },
          { 'strategy-template_loading': !loaded }
        )}
      >
        {loaded && (
          <div className="st-header">
            漏洞策略模板
            <Tooltip
              className="info"
              placement="right"
              overlayClassName={'page-title-desc'}
              title="添加漏洞策略后,可在新建任务时选择对应的漏洞策略模版"
            >
              <Icon type="exclamation-circle" />
            </Tooltip>
          </div>
        )}
        {body}
        <ConfigModal
          data={onedays}
          current={currentTemplate}
          visible={configModalVisible}
          onCancel={this.wrapOnConfigModalVisibleChange(false)}
          onSuccess={this.afterConfigStrategy}
        />
      </div>
    );
  }
}

export default StrategyTemplate;
